<!-- 地图模块初始化加载 -->
<template>
<div class="map-container">
    <!-- 地图 -->
    <div id="main_map" class="main-map">
        <div id="scaleBarDiv"></div>
    </div>
    <!-- 左侧工具条 -->
    <left-tools ref="leftTools"></left-tools>
    <!-- 头部搜索 -->
    <topsearch ref="topsearch"></topsearch>
    <!-- 右侧地图工具条 -->
    <right-map-tools ref="rightMapTools"></right-map-tools>

</div>
</template>

<script>
import * as esriLoader from "esri-loader";
import MapManager from "../../core/mapManager";

import leftTools from "./tools/leftTools.vue"
import topsearch from "./tools/topsearch.vue"
import rightMapTools from "./tools/mainMapTools.vue";

export default {
    name: "MapContainer",
    props: {},
    data() {
        return {
            initBaseMapType: "电子地图",
            mapView: null,
            active3D: false,
        };
    },

    components: {
        leftTools,
        topsearch,
        rightMapTools,
    },

    computed: {},

    methods: {
        //获取url地址中的某一个参数值
        _getUrlParam(paraName) {
            var url = document.location.toString();
            var arrObj = url.split("?");

            if (arrObj.length > 1) {
                var arrPara = arrObj[1].split("&");
                var arr;
                for (var i = 0; i < arrPara.length; i++) {
                    arr = arrPara[i].split("=");
                    if (arr != null && arr[0] == paraName) {
                        return arr[1];
                    }
                }
                return "";
            } else {
                return "";
            }
        },
        //地图初始化加载
        _initMap() {
            const self = this
            //1、视图存在则先进行移除
            if (this.mapView) {
                this.mapView.ui.empty();
                if (this.compass) this.compass.destroy();
                if (this.scaleBar) this.scaleBar.destroy();
                MapManager.removeMapViewByID("mainMap");
                this.mapView = null;
            }
            //2、加载地图相关资源
            esriLoader
                .loadModules([
                    "esri/Map",
                    "esri/views/MapView",
                    "esri/Basemap",
                    "esri/geometry/Point",
                    'esri/geometry/Polyline',
                    "esri/geometry/Polygon",
                    "esri/geometry/Extent",
                    "esri/layers/TileLayer",
                    "esri/layers/support/TileInfo",
                    "esri/layers/MapImageLayer",
                    "esri/layers/FeatureLayer",
                    "esri/layers/GraphicsLayer",
                    "esri/layers/WebTileLayer",
                    "esri/layers/WMTSLayer",
                    "esri/geometry/SpatialReference",
                    "esri/core/watchUtils",
                    "esri/widgets/ScaleBar",
                    "esri/widgets/Compass",
                    "esri/Graphic",
                    'esri/config',
                ])
                .then(([
                    Map,
                    MapView,
                    Basemap,
                    Point,
                    Polyline,
                    Polygon,
                    Extent,
                    TileLayer,
                    TileInfo,
                    MapImageLayer,
                    FeatureLayer,
                    GraphicsLayer,
                    WebTileLayer,
                    WMTSLayer,
                    SpatialReference,
                    watchUtils,
                    ScaleBar,
                    Compass,
                    Graphic,
                    esriConfig
                ]) => {
                    self.Map = Map
                    self.MapView = MapView
                    self.Basemap = Basemap
                    self.Point = Point
                    self.Polyline = Polyline
                    self.Polygon = Polygon
                    self.Extent = Extent
                    self.TileLayer = TileLayer
                    self.TileInfo = TileInfo
                    self.MapImageLayer = MapImageLayer
                    self.FeatureLayer = FeatureLayer
                    self.GraphicsLayer = GraphicsLayer
                    self.WebTileLayer = WebTileLayer
                    self.WMTSLayer = WMTSLayer
                    self.SpatialReference = SpatialReference
                    self.watchUtils = watchUtils
                    self.ScaleBar = ScaleBar
                    self.Compass = Compass
                    self.Graphic = Graphic
                    //设置静态资源
                    if (window.g.MapConfiguration.ArcGIS_Fonts_Path) {
                        esriConfig.fontsUrl = window.g.MapConfiguration.ArcGIS_Fonts_Path
                    }
                    //设置初始化范围                    
                    let initExtent = new Extent(window.g.MapConfiguration.InitExtent);
                    self.initExtent = initExtent.expand(1.1);
                    //设置底图资源
                    const configBaseMaps = window.g.MapConfiguration.BaseMaps;
                    configBaseMaps.sort((a, b) => {
                        return b.order - a.order;
                    });
                    self.initBaseMapType = configBaseMaps[0] ? configBaseMaps[0].class : "电子地图";
                    let tileInfo = null;
                    if (window.g.MapConfiguration.TileInfoOptions) {
                        tileInfo = new TileInfo(window.g.MapConfiguration.TileInfoOptions)
                    }
                    const baseLayers = [];
                    configBaseMaps.forEach((m, index) => {
                        let initLayer = null;
                        switch (m.type) {
                            case "tile":
                                if (tileInfo && m.isCustomTile) {
                                    initLayer = new self.TileLayer({
                                        url: m.url,
                                        title: m.title,
                                        tileInfo: tileInfo,
                                    });
                                } else {
                                    initLayer = new TileLayer({
                                        url: m.url,
                                        title: m.title,
                                    });
                                }
                                break;
                            case "feature":
                                initLayer = new self.FeatureLayer({
                                    url: m.url,
                                    title: m.title,
                                });
                                break;
                            case "wmts":
                                initLayer = new self.WMTSLayer({
                                    url: m.url,
                                    title: m.title,
                                    customParameters: m.customParameters,
                                    activeLayer: m.activeLayer,
                                });
                                break;
                            case "web-tile":
                                let urlTemplate = m.urlTemplate;
                                initLayer = new self.WebTileLayer({
                                    urlTemplate: urlTemplate,
                                    title: m.title,
                                    tileInfo: tileInfo,
                                    fullExtent: new self.Extent({
                                        xmax: 180,
                                        xmin: -180,
                                        ymax: 90,
                                        ymin: -90,
                                        spatialReference: {
                                            wkid: 4490,
                                        },
                                    }),
                                    spatialReference: tileInfo.spatialReference,
                                    subDomains: m.subDomains,
                                });
                                break;
                            default:
                                initLayer = new self.MapImageLayer({
                                    url: m.url,
                                    title: m.title,
                                });
                                break;
                        }
                        if (initLayer) {
                            initLayer.isBaseMap = true;
                            initLayer.id = "BaseMap_" + index;
                            initLayer.class = m.class;
                            initLayer.visible = m.class === self.initBaseMapType
                            baseLayers.push(initLayer)
                        }
                    });

                    const baseMaps = new Basemap({
                        baseLayers: baseLayers,
                        title: '底图',
                        id: 'BaseMaps',
                    })
                    const mainMap = new Map({
                        basemap: baseMaps
                    })
                    self.mapView = new MapView({
                        map: mainMap,
                        container: 'main_map',
                        extent: initExtent.expand(0.8),
                        spatialReference: initExtent.spatialReference,
                        constraints: {
                            rotationEnabled: false
                        }
                    })
                    if (window.g.MapConfiguration.InitExtent.zoom) {
                        self.mapView.zoom = window.g.MapConfiguration.InitExtent.zoom;
                    }
                    if (window.g.MapConfiguration.InitExtent.scale) {
                        self.mapView.scale = window.g.MapConfiguration.InitExtent.scale;
                    }
                    //移除默认小组件
                    self.mapView.ui.empty("top-left");
                    self.mapView.ui.remove("attribution");
                    //设置添加比例尺
                    self.scaleBar = new self.ScaleBar({
                        id: "scaleBar",
                        container: "scaleBarDiv",
                        view: self.mapView,
                        unit: "metric",
                    });
                    self.mapView.ui.add(self.scaleBar, {
                        position: "bottom-left",
                    });
                    //设置通用弹框样式
                    self.mapView.popup = {
                        highlightEnabled: true,
                        updateLocationEnabled: true,
                        dockEnabled: false,
                        dockOptions: {
                            buttonEnabled: false,
                            breakpoint: true,
                            position: 'bottom-center'
                        },
                    }
                    //地图视图资源加载完成后操作                    
                    self.mapView.when(() => {
                        //保存视图其它组件方可使用
                        MapManager.saveMapView(self.mapView, "mainMap");
                        // // MapDrawHelper.initDrawTool(self.mapView);
                        // MeasureHelper.initMeasureTool(self.mapView);
                        self._reloadComponents();
                        self._goInitExtent();
                        //添加市级、区县要素
                        self.cityDivisions = MapManager.getAdministrativeDivisions()
                        self.blockDivisions = MapManager.getAdministrativeDivisions(1)
                        //添加遮罩
                        // self._setShade() //暂时屏蔽-20231215
                    })

                }).catch((e) => {
                    console.error("初始化地图出错——");
                    console.error(e);
                });

        },
        //设置初始化范围
        _goInitExtent() {
            if (window.g.MapConfiguration.FullViewInfo) {
                const p = new this.Point({
                    x: window.g.MapConfiguration.FullViewInfo.center.x,
                    y: window.g.MapConfiguration.FullViewInfo.center.y,
                    spatialReference: this.mapView.spatialReference,
                });
                this.mapView.goTo({
                    target: p,
                    zoom: window.g.MapConfiguration.FullViewInfo.zoom
                }, {
                    easing: "ease-out",
                    duration: 1000
                });
            } else {
                if (this.initExtent && this.mapView) {
                    this.mapView.goTo(this.initExtent, {
                        easing: "ease-out",
                        duration: 1000,
                    });
                }
            }
        },
        //根据用户设置对应的省、市、县掩膜遮罩
        _setShade() {
            const self = this
            //1、获取当前用户的范围
            let cityCode = self._getUrlParam("cityCode")
            let level = "省级"
            if (cityCode.substring(0, 12) === "330000000000") {
                level = "省级"
            } else if (cityCode.substring(4, 12) === "00000000") {
                level = "市级";
            } else if (cityCode.substring(6, 12) === "000000") {
                level = "区县";
            } else if (cityCode.substring(9, 12) === "000") {
                level = "乡镇";
            } else {
                level = "乡镇";
                cityCode = cityCode.substring(0, 8) + "0000";
            }

            let markGeoSet = null;
            if (level == "省级") {
                //添加边界线
                self.divisionBaseLayerLine = new self.GraphicsLayer({ //用于画边界线,否则看不到边界
                    id: "xzqhGraphicsLayerLine",
                });
                self.divisionBaseLayerLine.class = "isBase";
                self.mapView.map.addMany([self.divisionBaseLayerLine]);
                self.cityDivisions.forEach(ele => {
                    let division1 = Object.assign({}, ele);
                    const g = new self.Graphic({
                        geometry: division1.geometry,
                        symbol: {
                            type: "simple-fill",
                            color: "rgba(255, 255, 255, 0)",
                            outline: {
                                color: 'rgba(163, 224, 255, 1)',
                                width: 2,
                            },
                        },
                    });
                    self.divisionBaseLayerLine.add(g);
                })
                self.mapView.constraints.minScale = window.g.MapConfiguration.XZQH_ScaleLimit[level];
                return;
            } else if (level == "市级") {
                for (let index = 0; markGeoSet == null && index < self.cityDivisions.length; index++) {
                    const element1 = self.cityDivisions[index];
                    let division1 = Object.assign({}, element1);
                    if (division1.attributes.code.substring(0, 4) == cityCode.substring(0, 4)) {
                        markGeoSet = division1.geometry
                        break;
                    }
                }
            } else if (level == "区县") {
                for (let index2 = 0; markGeoSet == null && index2 < self.blockDivisions.length; index2++) {
                    const element2 = self.blockDivisions[index2];
                    let division2 = Object.assign({}, element2);
                    if (division2.attributes.code.substring(0, 6) == cityCode.substring(0, 6)) {
                        markGeoSet = division2.geometry
                        break;
                    }
                }
            }

            //2、新建遮罩图层
            self.divisionBaseLayer = new self.GraphicsLayer({
                id: "xzqhGraphicsLayer",
                opacity: 1,
                blendMode: "destination-in",
                effect: "brightness(1.5) drop-shadow(0, 0px, 12px)",
            });
            self.divisionBaseLayer.class = "isBase";
            self.divisionBaseLayerLine = new self.GraphicsLayer({ //用于画边界线,否则看不到边界
                id: "xzqhGraphicsLayerLine",
            });
            self.divisionBaseLayerLine.class = "isBase";
            self.mapView.map.addMany([self.divisionBaseLayer, self.divisionBaseLayerLine]);

            //3、添加图形范围
            const g = new self.Graphic({
                geometry: markGeoSet,
                symbol: {
                    type: "simple-fill",
                    color: "rgba(255, 255, 255, 1)",
                    outline: {
                        color: 'rgba(163, 224, 255, 1)',
                        width: 2,
                    },
                },
            });
            let g2 = g.clone();
            g2.symbol.color = "rgba(255, 255, 255, 0)"
            self.divisionBaseLayer.add(g);
            self.divisionBaseLayerLine.add(g2);
            self.mapView.constraints.geometry = markGeoSet.extent.expand(1.2);
            self.mapView.goTo({
                target: markGeoSet.extent.expand(1.2)
            }, {
                easing: "ease-out",
                duration: 1000
            });

            //4、限制显示对应的范围
            self.mapView.constraints.minScale = window.g.MapConfiguration.XZQH_ScaleLimit[level];
        },
        //右侧工具条初始化
        _reloadComponents() {
            // this.$refs.rightMapTools.initToolsData();
            // this.$refs.rightBottomSmallTools.init();
        },

    },

    mounted() {
        this._initMap();
    },

    beforeDestroy() {
        this.mapView.graphics.removeAll()
    },

}
</script>

<style lang="scss" scoped>
.map-container {
    position: relative;
    z-index: 10;
    height: 100vh;
    width: 100vw;
    background-size: 100% 100%;
    overflow: hidden;
    float: left;
}

.main-map {
    width: 100%;
    height: 100%;
    background-color: white;
}
</style>
